<?php
/**
 * Created by PhpStorm.
 * Author: 赵凯
 * Date: 2019/12/9
 * Time: 18:11
 */

namespace api\install\controller;


use api\common\model\RlEtAzdModel;
use api\common\model\UserModel;
use api\common\service\CurlService;
use api\common\service\MsgService;
use cmf\controller\RestBaseController;
use think\Cache;
use think\Config;
use think\Controller;
use think\Validate;
use \Firebase\JWT\JWT;

class LoginController extends Controller
{
    //小程序的参数
    protected $appid = '';
    protected $secret = '';
    //密码的后缀
    protected $suffix= '';

    public function Login(){

        $validate = new Validate([
            'code'  => 'require',
            'phone' =>'require|length:11|regex:/^1[3456789]\d{9}$/',
//            'password' => 'require',
            'msg_code' => 'require',
        ]);

        $validate->message([
            'code.require'           => '缺少参数code!',
            'phone.require' => '请输入手机号或用户名!',
            'phone.length' => '手机号位数不对!',
            'phone.regex' => '手机号格式不对!',
//            'password.require' => '请输入您的密码!',
            'msg_code.require' => '请输入您的验证码!',

        ]);
        $data['code'] = trim($this->request->param('code',''));
        $data['phone'] = trim($this->request->param('phone',''));
        $data['msg_code'] = trim($this->request->param('msg_code',''));

        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $user_where['PHONE'] = $data['phone'];
        $cache_code =Cache::get('code'.$data['phone']);
        if($cache_code!=$data['msg_code'])$this->error('验证码不正确或已失效');
        $res = RlEtAzdModel::where($user_where)->find();
        if(!$res) $this->error('该用户不存在');
//        if($res['user_pass'] != md5($data['password'].$this->suffix)) $this->error('账号或密码错误');
        if($res['ACTIVE_FLAG']==0) $this->error('该用户禁止登陆');
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->appid}&secret={$this->secret}&js_code={$data['code']}&grant_type=authorization_code";
        $weixin =  CurlService::curlRequest($url);
        $jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
        $array = get_object_vars($jsondecode);//转换成数组
        if (!empty($array['errcode'])) {
            $this->error('操作失败!');
        };
        $openid = $array['openid'];//输出openid
        $token = [
            "iss"=>"",  //签发者 可以为空
            "aud"=>"", //面象的用户，可以为空
            "iat" => time(), //签发时间
            "nbf" => time(), //在什么时候jwt开始生效  （这里表示生成100秒后才生效）
            "exp" => time()+7200, //token 过期时间
            "uid" => $res //记录的userid的信息，这里是自已添加上去的，如果有其它信息，可以再添加数组的键值对
        ];

        $jwt = JWT::encode($token,Config::get('app.jwt')['key'],"HS256"); //根据参数生成了 token

        return json([
            "token"=>$jwt
        ]);

    }
    public function send()
    {
        $mobile = request()->param('mobile', '', 'intval');
        // 验证手机号
        if (!preg_match("/^1\d{10}$/", $mobile)) {

            $this->error('手机号错误');
        }
        $code =  rand(1000,9999);
        Cache::set('user_code'.$mobile,$code,300);
        $msg_send = new MsgService();
        $res = $msg_send->singlesender($code,$mobile);
        if($res['result'] == 0) {
            Cache::set('user_code'.$mobile,$code,300);
            $this->success('发送成功');
        }
        $this->error('发送失败');



    }

}